﻿using Mad.Core.DomainServices;
using Mad.Core.Model;
using Mad.Infrastructure.ApplicationServices;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mad.Infrastructure.DomainServices
{
    public class TableRepository: IRepository
    {
        private readonly IAppConfig appConfig;

        public TableRepository(IAppConfig appConfig)
        {
            this.appConfig = appConfig;
        }

        public DataSet GetDataByQuery(ProviderInfo provider, string query)
        {
            SqlConnectionStringBuilder builder = appConfig.GetConnectionStringBuilder(provider);
            Database db = new SqlDatabase(builder.ConnectionString);
            DbConnection conn = db.CreateConnection();
            conn.Open();

            var ds = new DataSet();
            using(DbCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;
                ds = db.ExecuteDataSet(cmd);
            }

            return ds;
        }
    }
}
